from flask import current_app,abort
import hashlib
import traceback
import time

def sign(data):
    try:
        appkey = current_app.config['STRIPE_API_KEY']
        data.pop('sign')
        # 排序
        data = sorted(data.keys())
        signstr = appkey
        for index, item in data.items():
            signstr += index + item
        signstr += appkey
        # 创建md5对象
        hl = hashlib.md5()
        # 此处必须声明encode
        # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
        hl.update(signstr.encode(encoding='utf-8'))
        sign = hl.hexdigest().upper()
        return sign
    except Exception as e:
        print('### 生成签名异常 ###')
        print("traceback:", traceback.format_exc())
        # 抛出异常，只取提示的
        abort(500, abort_msg(e))
    
def checkSign(data):
    try:
        # 检查请求时间
        if int(time.time()) - data.get('timestamp') >= 30:
            return {'message':'请求超时'},404
        sign = data.get('sign')
        data.pop('sign')
        # 排序
        data = sorted(data.keys())
        signstr = appkey
        for index, item in data.items():
            signstr += index + item
        signstr += appkey
        # 创建md5对象
        hl = hashlib.md5()
        # 此处必须声明encode
        # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
        hl.update(signstr.encode(encoding='utf-8'))
        newsign = hl.hexdigest().upper()
        return True if sign == newsign else False
    except Exception as e:
        print('### 验证签名异常 ###')
        print("traceback:", traceback.format_exc())
        # 抛出异常，只取提示的
        abort(500, abort_msg(e))